package com.rightsidetech.system.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.system.dtos.request.SysUpdateStatusReq;
import com.rightsidetech.system.dtos.request.agent.SysAgentAdminInfoAddReq;
import com.rightsidetech.system.dtos.request.agent.SysAgentInfoPageReq;
import com.rightsidetech.system.dtos.request.agent.SysAgentInfoUpdateReq;
import com.rightsidetech.system.dtos.response.agent.SysAgentInfoResp;
import com.rightsidetech.system.dtos.response.agent.SysDropDownNameResp;
import com.rightsidetech.system.entity.*;
import com.rightsidetech.system.mapper.*;
import com.rightsidetech.system.service.SysAdminAgentService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: yhr
 * @Date: 2021-11-01 16:59
 */

@Service("sysAdminAgentServiceImpl")
public class SysAdminAgentServiceImpl implements SysAdminAgentService {
    @Resource
    private SysAgentLoginInfoMapper sysAgentLoginInfoMapper;
    @Resource
    private SysAgentRoleMapper sysAgentRoleMapper;
    @Resource
    private SysAgentRoleAccountMapper sysAgentRoleAccountMapper;
    @Resource
    private SysAgentRoleResourceMapper sysAgentRoleResourceMapper;

    @Override
    public ResponseData<PageInfo<SysAgentInfoResp>> pageAgent(SysAgentInfoPageReq req, Long loginInfoId) {
        SysAgentLoginInfo loginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (StringUtils.isEmpty(loginInfo)) {
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<SysAgentInfoResp> page = sysAgentLoginInfoMapper.pageAgent(req,loginInfo.getAgentInfoId());
        return ResponseData.success(new PageInfo<>(page));
    }

    @Override
    public ResponseData saveAgentAdminInfo(SysAgentAdminInfoAddReq req, Long loginInfoId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAgentLoginInfo loginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (StringUtils.isEmpty(loginInfo)) {
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        List<Long> list = sysAgentRoleMapper.selectLongList(loginInfo.getAgentInfoId());
        if (ObjectUtils.isEmpty(list) || !list.contains(req.getRoleId())){
            return ResponseData.fail(CodeIdEnum.NOROLE);
        }
        List<Long> longList = sysAgentLoginInfoMapper.selectNameMobile(req.getLoginName(), req.getMobileNo());
        if (!ObjectUtils.isEmpty(longList) || longList.size() > 0){
            return ResponseData.fail("系统中已存在帐号或手机号");
        }

        SysAgentLoginInfo agentLoginInfo = new SysAgentLoginInfo();
        agentLoginInfo.setLoginName(req.getLoginName());
        agentLoginInfo.setSalt(String.valueOf(Math.random() * 900000 + 100000));
        agentLoginInfo.setPassword(DigestUtils.md5DigestAsHex((req.getPassword() + agentLoginInfo.getSalt()).getBytes()));
        agentLoginInfo.setAgentInfoId(loginInfo.getAgentInfoId());
        agentLoginInfo.setUserName(req.getUserName());
        agentLoginInfo.setMobileNo(req.getMobileNo());
        agentLoginInfo.setIsAgent((byte) 0);
        agentLoginInfo.setCreaterName(loginInfo.getUserName());
        agentLoginInfo.setCreatedAt(new Date());
        sysAgentLoginInfoMapper.insertSelective(agentLoginInfo);

        SysAgentRoleAccount account = new SysAgentRoleAccount();
        account.setLoginInfoId(agentLoginInfo.getId());
        account.setRoleId(req.getRoleId());
        account.setCreatedAt(new Date());
        sysAgentRoleAccountMapper.insertSelective(account);
        return ResponseData.success();
    }

    @Override
    public ResponseData updateAgentInfo(SysAgentInfoUpdateReq req, Long loginInfoId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAgentLoginInfo loginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        List<Long> longs = getAgentId(loginInfoId);
        if (ObjectUtils.isEmpty(longs) || !longs.contains(req.getId())){
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }
        List<Long> list = sysAgentRoleMapper.selectLongList(loginInfo.getAgentInfoId());
        if (ObjectUtils.isEmpty(list) || !list.contains(req.getRoleId())){
            return ResponseData.fail(CodeIdEnum.NOROLE);
        }
        List<Long> longList = sysAgentLoginInfoMapper.selectNameMobile(req.getLoginName(), req.getMobileNo());
        for (Long id:longList) {
            if (!id.equals(req.getId())){
                return ResponseData.fail("系统中已存在帐号或手机号");
            }
        }
        SysAgentLoginInfo agentLoginInfo = new SysAgentLoginInfo();
        agentLoginInfo.setId(req.getId());
        agentLoginInfo.setLoginName(req.getLoginName());
        if (!StringUtils.isEmpty(req.getPassword())){
            agentLoginInfo.setSalt(String.valueOf(Math.random() * 900000 + 100000));
            agentLoginInfo.setPassword(DigestUtils.md5DigestAsHex((req.getPassword() + agentLoginInfo.getSalt()).getBytes()));
        }
        agentLoginInfo.setUserName(req.getUserName());
        agentLoginInfo.setMobileNo(req.getMobileNo());
        sysAgentLoginInfoMapper.updateByPrimaryKeySelective(agentLoginInfo);
        SysAgentRoleAccount agentRoleAccount = sysAgentRoleAccountMapper.selectByLoginId(req.getId());
        if (!ObjectUtils.isEmpty(agentRoleAccount)){
            SysAgentRole sysAgentRole = sysAgentRoleMapper.selectByPrimaryKey(agentRoleAccount.getRoleId());
            if (ObjectUtils.isEmpty(sysAgentRole)){
                return ResponseData.fail("未找到关联角色");
            }
            agentRoleAccount.setRoleId(req.getRoleId());
            agentRoleAccount.setUpdatedAt(new Date());
            sysAgentRoleAccountMapper.updateByPrimaryKeySelective(agentRoleAccount);
        }else {
            SysAgentRoleAccount roleAccount = new SysAgentRoleAccount();
            roleAccount.setRoleId(req.getRoleId());
            roleAccount.setCreatedAt(new Date());
            roleAccount.setLoginInfoId(loginInfo.getId());
            sysAgentRoleAccountMapper.insertSelective(roleAccount);
        }
        return ResponseData.success();
    }


    @Override
    public ResponseData delAgentInfo(DelReq req,Long loginInfoId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAgentLoginInfo info = sysAgentLoginInfoMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtils.isEmpty(info) || info.getIsDeleted() == 1){
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }
        List<Long> longs = getAgentId(loginInfoId);
        if (ObjectUtils.isEmpty(longs) || !longs.contains(req.getId())){
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }
        sysAgentLoginInfoMapper.updateStatus(req.getId(), (byte) 1, info.getStatus());
        sysAgentRoleAccountMapper.deleteByLoginId(req.getId());
        return ResponseData.success();
    }

    @Override
    public ResponseData updateAgentInfoStatus(SysUpdateStatusReq req,Long loginInfoId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAgentLoginInfo info = sysAgentLoginInfoMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtils.isEmpty(info)){
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }
        List<Long> longs = getAgentId(loginInfoId);
        if (ObjectUtils.isEmpty(longs) || !longs.contains(req.getId())){
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }
        if (info.getStatus().equals(req.getStatus())){
            return ResponseData.fail(CodeIdEnum.REPEATSTATUS);
        }
        sysAgentLoginInfoMapper.updateStatus(req.getId(), info.getIsDeleted(), req.getStatus());
        return ResponseData.success();
    }

    private List<Long> getAgentId(Long loginInfoId){
        SysAgentLoginInfo sysAgentLoginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(sysAgentLoginInfo)){
            return null;
        }
        List<Long> longs = sysAgentLoginInfoMapper.selectOperateList(sysAgentLoginInfo.getAgentInfoId());
        return longs;
    }

    @Override
    public ResponseData<List<SysDropDownNameResp>> selectList(Long loginInfoId) {
        SysAgentLoginInfo sysAgentLoginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(sysAgentLoginInfo)){
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }
        return ResponseData.success(sysAgentLoginInfoMapper.selectAgentList(sysAgentLoginInfo.getAgentInfoId()));
    }

    @Override
    public SysAgentInfoResp selectById(Long id) {
        return sysAgentLoginInfoMapper.selectById(id);
    }
}
